package controllers

import java.io.File

import javax.inject.Inject
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}
import tool.{FormTool, Tool}
import utils.Utils
import implicits.Implicits._

import scala.concurrent.ExecutionContext.Implicits.global


/**
 * Created by Administrator on 2019/8/8
 */
class ToolController @Inject()(cc: ControllerComponents, formTool: FormTool) extends AbstractController(cc) {

  def downloadExampleData = Action {
    implicit request =>
      val data = formTool.fileNameForm.bindFromRequest().get
      val exampleDir = Tool.exampleDir
      val resultFile = new File(exampleDir, data.fileName)
      Ok.sendFile(resultFile).withHeaders(
        CONTENT_DISPOSITION -> s"${
          Tool.getContentDisposition(resultFile.getName)
        }",
        CONTENT_TYPE -> "application/x-download"
      )
  }

  def getChildrenNodes = Action { implicit request =>
    val data = FormTool.nodeForm.bindFromRequest().get
    val dir = new File(data.id)
    val nodes = dir.myListFiles.map { x =>
      if (x.isDirectory) {
        Map("id" -> x.getAbsolutePath, "pId" -> x.getParentFile.getAbsolutePath, "name" -> x.getName,
          "icon" -> "/assets/images/baidu_folder.png", "isParent" -> x.isParent.toString)
      } else Map[String, String]()
    }.filter(!_.isEmpty)
    Ok(Json.toJson(nodes))
  }

}
